package br.com.winesys.geta.databinding.component.editor;

import java.awt.Toolkit;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;

public class LimitedTextField extends JTextField {

    public LimitedTextField() {
    }

    public LimitedTextField(int limit) {
        super();
        this.setLimit(limit);
        this.addFocusListener(new FocusAdapter() {
			@Override
			public void focusGained(FocusEvent evt) {
				if (!evt.isTemporary()){
					LimitedTextField.this.selectAll();
				}
			}
		});

    }

    public void setLimit(int limit) {
        if (limit > 0) {
            this.setDocument(new LimitedDocument(limit));
        } else {
            this.setDocument(new PlainDocument());
        }
    }

    private class LimitedDocument extends PlainDocument {

        private int limit = 0;

        public LimitedDocument(int limit) {
            this.limit = limit;
            setDocumentFilter(new DocumentFilter() {

                @Override
                public void insertString(FilterBypass fb, int offs, String str, AttributeSet a) throws BadLocationException {
                    if ((fb.getDocument().getLength() + str.length()) <= LimitedDocument.this.limit) {
                        super.insertString(fb, offs, str, a);
                    } else {
                        Toolkit.getDefaultToolkit().beep();
                    }
                }

                @Override
                public void replace(FilterBypass fb, int offs, int length, String str, AttributeSet a) throws BadLocationException {
                    if ((fb.getDocument().getLength() + str.length() - length) <= LimitedDocument.this.limit) {
                        super.replace(fb, offs, length, str, a);
                    } else {
                        Toolkit.getDefaultToolkit().beep();
                    }
                }
            });
        }
    }
}


